//
//  MAStudentEditController.m
//  meiang_edu
//
//  Created by hfcb on 2018/9/11.
//  Copyright © 2018年 com.meiang.meiang_edu. All rights reserved.
//

#import "MAStudentEditController.h"
#import "MAMgrPopView.h"
#import "MADataPickView.h"
#import <zhPopupController.h>
#import "MABabyModel.h"
#import "OssService.h"
#import "NSString+Js.h"

@interface MAStudentEditController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *bgIcon;
@property (weak, nonatomic) IBOutlet UIImageView *faceIcon;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
@property (weak, nonatomic) IBOutlet UITextField *nickNameTF;

@property (strong, nonatomic) UIActionSheet *actionSheet;
/** bgImgUrl */
@property(nonatomic,copy) NSString *bgImgUrl;
/** faceImgUrl */
@property(nonatomic,copy) NSString *faceImgUrl;

@end

@implementation MAStudentEditController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self hiddenTabbar:YES];
    [self setupBasic];
    
    [self setupTableView];
    
    [self bindData];
    
}

- (void)setupBasic {
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(saveDidClick) image:@"savebutton_logo" highImage:@"savebutton_logo"];
}

- (void)bindData {
    [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,self.babyModel.cbackground]] placeholderImage:[UIImage imageNamed:@""]];
    [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IMG_OSS,self.babyModel.ps_id]] placeholderImage:[UIImage imageNamed:@"homepage_navigationbar_picture"]];
    self.nameTF.text = self.babyModel.chname;
    self.birthdayLabel.text = self.babyModel.chbirthday;
    self.nickNameTF.text = self.babyModel.chnickname;
    self.sexLabel.text = self.babyModel.aschgender;
}

- (void)setupTableView {
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 4)];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = PROJECT_LIGHT_GRAY_COLOR;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)saveDidClick {
    DLog(@"");
    NSString *name = self.nameTF.text;
    if (!name.length) {
        [MBManager showBriefAlert:@"名称不能为空"];
        return;
    }
    NSString *birthday = self.birthdayLabel.text;
    if ([birthday isEqualToString:@"请选择"]) {
        [MBManager showBriefAlert:@"生日不能为空"];
        return;
    }
    NSString *nickname = self.nickNameTF.text;
    if (!nickname.length) {
        [MBManager showBriefAlert:@"昵称不能为空"];
        return;
    }
    NSString *sex = self.sexLabel.text;
    if ([sex isEqualToString:@"请选择"]) {
        [MBManager showBriefAlert:@"性别不能为空"];
        return;
    }
    MAUserInfo *userinfo = [MAUserInfoTool userinfo];
    //    if (!userinfo.token) {
    //        [MBManager showBriefAlert:@"登录状态已过期,请重新登录"];
    //        return;
    //    }
    [MBManager showLoading];
//    "id": "5232A467-8FA2-4D8A-8E6B-CE3224756426",学生guid
//    "ccode": "XS0013",学生编号
//    "chname": "徐娇娇",学生姓名
//    "cpinyin": "xujiaojiao",拼音
//    "chnickname": "娇娇",昵称
//    "chphone": null,联系电话
//    "aschgender": "女",性别
//    "chidentitycard": "372323201108217325",身份证
//    "ps_id": "0A20CAD2-5D5D-4BD8-AFA2-8D0DCEC1C40E",头像guid
//    "cbackground":""背景图片ID
//    "chbirthday": "2011-03-23",出生日期
//    "cnotes": null,

    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    
    body[@"id"] = self.babyModel.ID;
    body[@"ccode"] = self.babyModel.ccode;
    body[@"chname"] = name;
    body[@"chnickname"] = nickname;
    body[@"aschgender"] = sex;
    body[@"chbirthday"] = birthday;
    body[@"ps_id"] = self.faceImgUrl.length ? self.faceImgUrl : self.babyModel.ps_id;
    body[@"cbackground"] = self.bgImgUrl.length ? self.bgImgUrl : self.babyModel.cbackground;
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSMutableURLRequest *req;
    if ([self.title isEqualToString:@"添加宝宝"])
    {
        req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BABY_ADD,self.jigouModel.ID] parameters:nil error:nil];
    }
    else
    {
        req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:CHILDREN_UPDATE parameters:nil error:nil];
    }
    [req setValue:@"application/text" forHTTPHeaderField:@"Content-Type"];
    [req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [req setValue:@"token" forHTTPHeaderField:userinfo.token];
    
    [req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    [[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [MBManager hideAlert];
        if (!error) {
            NSInteger msgcode = [responseObject[@"msgcode"] integerValue];
            NSString *message = responseObject[@"message"];
            if (msgcode == 1) {
                [MBManager showBriefAlert:message];
                self.babyModel.chname = name;
                self.babyModel.chbirthday = birthday;
                self.babyModel.aschgender = sex;
                self.babyModel.chnickname = nickname;
                if (self.faceImgUrl.length) {
                    self.babyModel.ps_id = self.faceImgUrl;
                }
                if (self.bgImgUrl.length) {
                    self.babyModel.cbackground = self.bgImgUrl;
                }
                self.navigationItem.rightBarButtonItem = nil;
            } else {
                [MBManager showBriefAlert:message];
            }
            DLog(@"Reply JSON: %@", responseObject);
            if ([self.title isEqualToString:@"添加宝宝"])
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } else {
            DLog(@"Error: %@, %@, %@", error, response, responseObject);
            [MBManager showBriefAlert:@"网络错误"];
        }
    }] resume];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    if (row == 0) {
        DLog(@"换背景");
        [self chooseIcon];
    } else if (row == 1) {
        DLog(@"换头像");
        [self chooseIcon];
    } else if (row == 3) {
        DLog(@"日期");
        
        MADataPickView *popView = [MADataPickView datePickView:^(NSString *date) {
            self.birthdayLabel.text = date;
            [self.zh_popupController dismiss];
        } cancelBlock:^(NSString *date) {
            [self.zh_popupController dismiss];
        }];
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
    } else if (row == 5) {
        DLog(@"性别");
        
        MAMgrPopView *popView = [MAMgrPopView popViewWithTitles:@[@"男", @"女"] clickBlock:^(NSInteger clickIdx) {
            DLog(@"============%ld",clickIdx);
            self.sexLabel.text = clickIdx == 0 ? @"男" : @"女";
            [self.zh_popupController dismiss];
        }];
        popView.layer.cornerRadius = 10;
        popView.layer.masksToBounds = YES;
        self.zh_popupController = [[zhPopupController alloc] init];
        self.zh_popupController.dismissOnMaskTouched = YES;
        self.zh_popupController.dismissOppositeDirection = YES;
        self.zh_popupController.slideStyle = zhPopupSlideStyleShrinkInOut2;
        [self.zh_popupController presentContentView:popView duration:0.35 springAnimated:YES];
    }
}

/**
 * 选择图片
 */
- (void)chooseIcon
{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 1) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    DLog(@"===========%ld",indexPath.row);
    
    // 上传头像
    OssService *ossService = [[OssService alloc] initWithEndPoint:OSS_ENDPOINT];
    NSString *category = OSS_CATEGORY;
    NSString *type = @"jpg";
    long long int timevalue = (long long int)([NSDate date].timeIntervalSince1970 * 1000);
    // 自己拼接key，用于标识对象。
    
    NSString *objectKey = [NSString uuidString];
    
    [ossService asyncPutImage:objectKey data:UIImageJPEGRepresentation(img, 0.5) success:^(NSString *imgUrl){
        DLog(@"%@",imgUrl);
        if (indexPath.row == 0) { // 背景
            self.bgImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.bgIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        } else { // 头像
            self.faceImgUrl = [[imgUrl componentsSeparatedByString:IMG_OSS] lastObject];
            [self.faceIcon sd_setImageWithURL:[NSURL URLWithString:imgUrl]];
        }
    } failure:^(NSString *errmsg, NSString *objectKey, NSData *uploadData) {
        DLog(@"%@",errmsg);
    }];
}
@end
